<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-纱支单价`"
		width="700px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1" label-width="110px" :show-message="false">
			<el-row ref="box1">
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="最小支数" prop="minValue">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.minValue }}</span>
						<jk-number-input v-else v-model="ruleForm.minValue" placeholder="最小支数" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="最大支数" prop="maxValue">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.maxValue }}</span>
						<jk-number-input v-else v-model="ruleForm.maxValue" placeholder="最大支数" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="纱名">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.keyword }}</span>
						<jk-select v-else v-model="ruleForm.keyword" :option-list="yarnNameList" class="width-100-percent" value-key-name="name" size="medium" placeholder="纱名" />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item class="margin-bottom-10" label="备注">
						<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.remark }}</span>
						<el-input v-else v-model="ruleForm.remark" :rows="1" type="textarea" placeholder="" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="24">
					<jk-table border :data="ruleForm.configItem" :height="dialogTableHeight - 20">
						<vxe-column :visible="pageType !== 'detail'" title="操作" align="center" field="operation" :width="80">
							<template slot="header">
								<div class="flex-center link-style" @click="onAddBtn">
									<span class="el-icon-plus"></span>
									<span>添加</span>
								</div>
							</template>
							<template slot-scope="scope">
								<el-button plain size="mini" icon="el-icon-minus" @click="onDeleteBtn(scope)"></el-button>
							</template>
						</vxe-column>
						<vxe-column title="工序" align="left" field="processId" :width="180">
							<template slot-scope="scope">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{ scope.row.processName }}</span>
								<jk-select v-else v-model="scope.row.processId" :option-list="processList" placeholder="工序"></jk-select>
							</template>
						</vxe-column>
						<vxe-column title="单价" align="right" field="unitPrice" :min-width="160">
							<template slot-scope="scope">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1">{{ scope.row.unitPrice }}</span>
								<jk-number-input v-else v-model="scope.row.unitPrice" size="small" placeholder="单价" />
							</template>
						</vxe-column>
					</jk-table>
				</el-col>
			</el-row>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { spinYarnCountPriceConfigCreate, spinYarnCountPriceConfigUpdate, spinYarnCountPriceConfigGet } from '../../../api/material/yarnCounPrice';
    import remoteSearchProductInput from '../../technology/order/components/remote-search-product-input/index';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    export default {
        mixins: [calHeight],
        components: { remoteSearchProductInput },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                processList: [],
                tableLoading: false,
                saveBtnLoading: false,
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                yarnNameList: [],
                ruleForm: {
                    'minValue': null,
                    'maxValue': null,
                    'auditState': 0,
                    'remark': '',
                    'keyword': '',
                    'configItem': []
                },
                rules: {
                    keyword: [{ required: true, trigger: 'change' }],
                    minValue: [{ required: true, trigger: 'change' }],
                    maxValue: [{ required: true, trigger: 'change' }],
                    criterion: [{ required: true, trigger: 'change' }],
                    tenPrice: [{ required: true, trigger: 'change' }]
                },
                defaultRowData: {
                    'processId': '',
                    'processCode': '',
                    'processName': '',
                    'unitPrice': 0
                }
            };
        },
        methods: {
            onDeleteBtn(scope) {
                this.ruleForm.configItem.splice(scope.rowIndex, 1);
            },
            onAddBtn() {
                this.ruleForm.configItem.push(JSON.parse(JSON.stringify(this.defaultRowData)));
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) {
                    params.auditState = 1;
                    delete params.id;
                }
                let colorItem = {};
                params.configItem.forEach(x => {
                    colorItem = this.processList.find(k => k.id === x.processId) || {};
                    x.processCode = colorItem.code;
                    x.processName = colorItem.name;
                });
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? spinYarnCountPriceConfigCreate : spinYarnCountPriceConfigUpdate;
                this.saveBtnLoading = true;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinYarnCountPriceConfigGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.configItem = resData.configItem || [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getYarnNameListRequest() {
                return systemBusinessDictPage({
                    categoryCode: 'YARN_NAME'
                }).then(res => {
                    if (res.data.status === 200) {
                        this.yarnNameList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.processList = this.$store.state.user.userProcess.processList || [];
                await this.getYarnNameListRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
